package com.rongc.client.core.pay.alipay.util;

import com.rongc.client.core.utils.DateUtil;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

public class OrderInfoUtil2_0 {
	public static final String RSA2_PRIVATE = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDAYvOx0W270pd5rF+o5SewkqBo6nvfJyRkeMnnFD24mFfxqJ/py2rVLKCPwf1AjFNaxMOXRhC/LDnJvzZUdTaR3tK0f5LGnzn5ysMoqGDNp2X/AQ1XpYKLMXxyUJaW+LgBU/Eonl80r833Nvwp2FE7ErbiST5+Zy7wQ+Tx2u1i4HHIMVVKEnq1TyHooltHy3kw/k4j/DQ6/94OLGbNpAi2FrigHn4omQQMAWHhvXbZxhBJ88e4F/fmJTqRUaTVws8WYxQ7O1CPVglpYVaIqMVRnp/hb4TqWCqrRFsupNbsH5ujS2rjzp3zWs6unrBpnG+Cy+a9NBc9QlO7W/vQt9x5AgMBAAECggEAaNuGB30mWiDF/sM8wElmAI9qbsSfD1m+NCTBpvkZSut9w3Es97ivWdEhEjmhVvUk2Ww1TtYZepkYRiW57v6T552TKl3+GdPfPY6OIDLl0DFVHk/sfcDwDf3C3mueKFsXr2GZJ5JqQcUwdXW6qvQEEjZ5B4z0SuDibIIU3t18VU8dsgFpOR1Xj8i/KL+H0N+Rxpsd6u+su7hfjdswCVxwnhtUVZFY8KDJLkfw8VMauYtqnK19r2gMVziFf3ALiB3oBqyLAd7M24mHClff3jHocBeRn5lKxymPfgGrz/UqVdrpGmgOm2ybetEWa5Y09xNCOBEnhdOrCtT/e0FLXS2igQKBgQDkLi0BgOxyby81zGwwFdz/oTsORwFRoIYf6xxvqrJhoksdsF13QvThsUtrbpBKvQphDB1l8LE0dOCt+7oux+BEMkf+8bdpfHdJn7CC/rFkSNrSntSyW/1rRz9C7RnlWgUTJSjFdAQXgCIZyRSfAlWmIkgugM1GB8QYWbo+dZZvXQKBgQDX15nVWCbjMupSYoNzuIAzdEOlpX9GDhVTcxUGpEJdq6Whz28MgG7MwpfswFHzxq/YAYU8eeamjQpSC7gQOfcRQER3g1pmvdqo8NuyacnsHTu75Mi7C6hGIXIh7xaYR1vYUnAZK7Yt3zUkm9S2xstzPHvs0bxpcZRnaacyRct7zQKBgGKncD/5LMGhPqkk9BWqLj27yNu4aWKQY80DCu1gwPUjhRSV/yMkKNo3nGMbj3kw2H7zDPbZJNSIP+gZMPsu4dC6aJRaj7Ek5jJHv7ozQiEYurtbfpyK1zt9t2VJO+wEirMnWsRcD7TVamj5nlfNW5iTs9+fQqEnlGnuyW5dyqflAoGBAK1LUx1xezdrB6tBoRzmAzhMnot+RqNuZzzq5vTAKPCgAYnay+QTseIAUo4pEyNQYJpjDiAyFzedga3B7vRINc/J866o7YoT4F1HlHy4ZwCFsBH5bBiREXfNHp+UIGX+1QTnm0z6RXiq/zX3T1+4WFybMTxAYK+gG3Cz6SN52hf5AoGBAMaDk4JzGVqP6rcBEyULQmtWQLrb/Y1h1WXC5MwwYf8Qk1cBOqf+G13ZE5KaCxmCjcb7wCPCmn5VbYu3FcrQQDIS8w8/jzM0v0u22WYDi6+aCVyLumfuhhNGF9S9hhzXc/CsTLzaP5sDO6O/YUoM29HStgtiUtHCqpApUAZ7Q8o1";

	/**
	 * 构造授权参数列表
	 * 
	 * @param pid
	 * @param app_id
	 * @param target_id
	 * @return
	 */
	public static Map<String, String> buildAuthInfoMap(String pid, String app_id, String target_id, boolean rsa2) {
		Map<String, String> keyValues = new HashMap<String, String>();

		// 商户签约拿到的app_id，如：2013081700024223
		keyValues.put("app_id", app_id);

		// 商户签约拿到的pid，如：2088102123816631
		keyValues.put("pid", pid);

		// 服务接口名称， 固定值
		keyValues.put("apiname", "com.alipay.account.auth");

		// 商户类型标识， 固定值
		keyValues.put("app_name", "mc");

		// 业务类型， 固定值
		keyValues.put("biz_type", "openservice");

		// 产品码， 固定值
		keyValues.put("product_id", "APP_FAST_LOGIN");

		// 授权范围， 固定值
		keyValues.put("scope", "kuaijie");

		// 商户唯一标识，如：kkkkk091125
		keyValues.put("target_id", target_id);

		// 授权类型， 固定值
		keyValues.put("auth_type", "AUTHACCOUNT");

		// 签名类型
		keyValues.put("sign_type", rsa2 ? "RSA2" : "RSA");

		return keyValues;
	}

	/**
	 * 构造支付订单参数列表
	 * @param
	 * @param
	 * @param
	 * @return
	 */
	public static Map<String, String> buildOrderParamMap(JSONObject json) {
		Map<String, String> keyValues = new HashMap<String, String>();

		keyValues.put("app_id", json.optString("partner"));

		keyValues.put("biz_content", "{\"timeout_express\":\"30m\"," +
				"\"product_code\":\"QUICK_MSECURITY_PAY\"," +
				"\"total_amount\":\""+json.optString("total_fee")+"\"," +
				"\"subject\":\""+json.optString("subject")+"\"," +
				"\"body\":\""+json.optString("body")+"\"," +
				"\"out_trade_no\":\"" + json.optString("out_trade_no") +  "\"}");
		
		keyValues.put("charset", "utf-8");

		keyValues.put("method", "alipay.trade.app.pay");

		keyValues.put("sign_type", "RSA2");

		keyValues.put("timestamp", DateUtil.getCurrentDate(DateUtil.dateFormatYMDHMS));

		keyValues.put("notify_url", json.optString("return_url"));

		keyValues.put("version", "1.0");
		
		return keyValues;
	}
	
	/**
	 * 构造支付订单参数信息
	 * 
	 * @param map
	 * 支付订单参数
	 * @return
	 */
	public static String buildOrderParam(Map<String, String> map) {
		List<String> keys = new ArrayList<String>(map.keySet());

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < keys.size() - 1; i++) {
			String key = keys.get(i);
			String value = map.get(key);
			sb.append(buildKeyValue(key, value, true));
			sb.append("&");
		}

		String tailKey = keys.get(keys.size() - 1);
		String tailValue = map.get(tailKey);
		sb.append(buildKeyValue(tailKey, tailValue, true));

		return sb.toString();
	}
	
	/**
	 * 拼接键值对
	 * 
	 * @param key
	 * @param value
	 * @param isEncode
	 * @return
	 */
	private static String buildKeyValue(String key, String value, boolean isEncode) {
		StringBuilder sb = new StringBuilder();
		sb.append(key);
		sb.append("=");
		if (isEncode) {
			try {
				sb.append(URLEncoder.encode(value, "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				sb.append(value);
			}
		} else {
			sb.append(value);
		}
		return sb.toString();
	}

	/**
	 * 对支付参数信息进行签名
	 *
	 * @param map
	 *            待签名授权信息
	 *
	 * @return
	 */
	public static String getSign(Map<String, String> map) {
		List<String> keys = new ArrayList<String>(map.keySet());
		// key排序
		Collections.sort(keys);

		StringBuilder authInfo = new StringBuilder();
		for (int i = 0; i < keys.size() - 1; i++) {
			String key = keys.get(i);
			String value = map.get(key);
			authInfo.append(buildKeyValue(key, value, false));
			authInfo.append("&");
		}

		String tailKey = keys.get(keys.size() - 1);
		String tailValue = map.get(tailKey);
		authInfo.append(buildKeyValue(tailKey, tailValue, false));

		String oriSign = SignUtils.sign(authInfo.toString(), RSA2_PRIVATE, true);
		String encodedSign = "";

		try {
			encodedSign = URLEncoder.encode(oriSign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "sign=" + encodedSign;
	}
	
	/**
	 * 要求外部订单号必须唯一。
	 * @return
	 */
	private static String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
		Date date = new Date();
		String key = format.format(date);

		Random r = new Random();
		key = key + r.nextInt();
		key = key.substring(0, 15);
		return key;
	}

}
